<template>
  <ZForm ref="form" :model="values" :rules="rules" @success="login">
    <ZFormItem name="email" label="电子邮件" outline>
      <ZInput name="email" v-model="values.email" v-focus />
    </ZFormItem>
    <ZFormItem name="password" label="密码" outline>
      <ZInput name="password" v-model="values.password" type="password" />
    </ZFormItem>
    <ZFormItem name="code" label="验证码" outline>
      <ZInput name="code" v-model="values.code" />
      <img class="h-8 w-auto cursor-pointer" :src="src" @click="refresh" />
    </ZFormItem>
    <ZButton type="submit" class="w-full tracking-widest" size="large">
      登 录
      <svg
        class="w-4 h-4 ml-2"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 20 20"
        fill="currentColor"
      >
        <path
          fill-rule="evenodd"
          d="M10.293 3.293a1 1 0 011.414 0l6 6a1 1 0 010 1.414l-6 6a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-4.293-4.293a1 1 0 010-1.414z"
          clip-rule="evenodd"
        ></path>
      </svg>
    </ZButton>
  </ZForm>
</template>
<script lang="ts" setup>
import { ref, reactive, onActivated } from "vue";
import { useLocalStorage } from "@vueuse/core";

import { Rules, Values } from "@/pkg/validate";
import ZForm from "@/pkg/forms/ZForm.vue";
import { randId } from "@/pkg/utils";

import { request } from "./apis";

// const notification = useNotification();
const emit = defineEmits(["success"]);
const email = useLocalStorage("email", "");

const values = reactive({
    email: email.value,
    password: "",
    code: "",
  }),
  rules: Rules = {
    email: [
      {
        required: true,
        email: true,
      },
      {
        minLength: 3,
        maxLength: 20,
        message: "用户名必须在3到20个字符之间",
      },
    ],
    password: [
      {
        required: true,
        message: "请输入密码",
      },
      {
        minLength: 6,
        maxLength: 20,
        message: "用户密码必须在6到20个字符之间",
      },
    ],
    code: { required: true, message: "不能为空！" },
  },
  form = ref<InstanceType<typeof ZForm>>(),
  src = ref("/captcha.svg");
//
const login = async (values: Values) => {
    // ajax 发送 FormData 数据
    let { data } = await request("/login", {
      method: "POST",
      data: values,
    });
    if (data.success) {
      email.value = values.email;
      emit("success", data.object);
    } else {
      if (data.errors) {
        form.value?.setErrors(data.errors);
      }
      values.code = "";
    }
    refresh();
  },
  refresh = () => {
    src.value = "/captcha?r=" + randId();
  };

onActivated(() => {
  values.code = "";
  refresh();
});
// defineExpose({
//   submit,
// });
</script>
